package com.akk.business;

import com.akk.PayConstants;
import com.akk.common.enums.AccessEnums;
import com.akk.common.enums.Enums;
import com.akk.exception.RestBusinessException;
import com.akk.module.access.entity.Access;
import com.akk.module.access.entity.AccessBank;
import com.akk.module.access.entity.AccessBind;
import com.akk.module.access.service.AccessService;
import com.akk.module.avs.entity.*;
import com.akk.module.avs.enums.AvsPayVipStatus;
import com.akk.module.avs.enums.AvsTransferStatus;
import com.akk.module.avs.model.request.*;
import com.akk.module.avs.service.*;
import com.akk.module.hlbpay.model.*;
import com.akk.module.hlbpay.service.HlbService;
import com.akk.module.hlbpay.util.Disguiser;
import com.akk.module.hlbpay.util.HlbBeanUtils;
import com.akk.utils.DateUtils;
import com.akk.utils.IDUtils;
import com.akk.utils.RestResponse;
import com.akk.utils.rsa.RSAUtils;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by admin on 2017/11/11.
 * 合利宝快捷
 */
@Component
public class AvsHlbQuickBusiness {

    @Autowired
    private AccessService accessService;
    @Autowired
    private AvsCustomerService avsCustomerService;
    @Autowired
    private AvsPayOrderService avsPayOrderService;
    @Autowired
    private HlbService hlbService;
    @Autowired
    private AvsPayCashBindService avsPayCashBindService;
    @Value("${temp.path}")
    private String path;
    @Autowired
    private AvsPayVipConfigService avsPayVipConfigService;
    @Autowired
    private AvsPayVipService avsPayVipService;
    @Autowired
    private AvsPayAccessService avsPayAccessService;
    @Autowired
    private AvsPayBusiness payBusiness;
    @Value("${server.url}")
    private String serverUrl;

    @Value("${temp.path}")
    private String tempPath;

    private static final Logger log = LoggerFactory.getLogger("hlbQuick");

    // 创建支付订单
    public RestResponse createPay(CreatePayRequest request) {
        AvsCustomer customer = avsCustomerService.findByCustomerId(request.getPayerId());
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "信息错误");
        request.setIdCard(customer.getIdCard());
        request.setHoldName(customer.getCustomerName());
        List<AvsPayOrder> orders = avsPayOrderService.findByOrderNum(request.getOrderNum());
        if (orders.isEmpty()) {
            throw new RestBusinessException("订单号不存在");
        }
        AvsPayOrder order = orders.get(0);
        RestResponse restResponse = null;
        if (request.getGateway().equals(AccessEnums.gatewayEnum.HLB_QUICK.getValue())) {
            if (!StringUtils.isEmpty(request.getCvv2()) && request.getCvv2().length() > 3) {
                request.setCvv2(RSAUtils.decryptDataOnJava(request.getCvv2(), PayConstants.CARD_RSA_PRIVATE_KEY_PKCS8));
            }
            HlbCreateOrderRequest createOrder = new HlbCreateOrderRequest();
            createOrder.setP3_userId(order.getPayerId());
            createOrder.setP4_orderId(order.getOrderNum());
            createOrder.setP6_payerName(request.getHoldName());
            createOrder.setP8_idCardNo(request.getIdCard());
            createOrder.setP9_cardNo(request.getCardNum());
            createOrder.setP10_year(request.getYear());
            createOrder.setP11_month(request.getMonth());
            createOrder.setP12_cvv2(request.getCvv2());
            createOrder.setP13_phone(request.getPhone());
            createOrder.setP15_orderAmount(order.getAmountTotal().toString());
            createOrder.setP16_goodsName(order.getRemark());
            createOrder.setP17_goodsDesc(order.getRemark());
            createOrder.setP18_terminalType(request.getTerminalType());
            createOrder.setP19_terminalId(request.getTerminalId());
            createOrder.setP20_orderIp(request.getOrderIp());
            createOrder.setP23_serverCallbackUrl(serverUrl + "/thmlfApi/avs/hlbquick/hlbasyncpaynotify");
            restResponse = hlbService.createOrder(createOrder);
        }
        return restResponse;
    }

    // 发起支付（未绑卡）
    public RestResponse createPayNotBind(CreatePayNotBindRequest request) {
        AccessBind accessBind = accessService.findAccessBindById(request.getAccessBindId());
        AvsCustomer customer = avsCustomerService.findByCustomerId(request.getPayerId());
        if (accessBind == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "银行卡信息不存在");
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不存在");
        List<AvsPayOrder> orders = avsPayOrderService.findByOrderNum(request.getOrderNum());
        if (orders.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "订单不存在");
        AvsPayOrder order = orders.get(0);
        order.setPayBank(accessBind.getCardName());
        order.setPayCardNo(accessBind.getCardNum());
        avsPayOrderService.update(order);
        CreatePayRequest payRequest = new CreatePayRequest();
        payRequest.setHoldName(customer.getCustomerName());
        payRequest.setIdCard(customer.getIdCard());
        payRequest.setCardNum(accessBind.getCardNum());
        payRequest.setPhone(accessBind.getPhone());
        payRequest.setOrderNum(request.getOrderNum());
        payRequest.setGateway(request.getGateway());
        payRequest.setOrderIp(request.getOrderIp());
        payRequest.setRememberCard(1);
        payRequest.setTerminalType(request.getTerminalType());
        payRequest.setTerminalId(request.getTerminalId());
        payRequest.setPayerId(request.getPayerId());
        if (accessBind.getCardType().equals("X")) {
            if (!StringUtils.isEmpty(accessBind.getCvv2())) {
                accessBind.setCvv2(RSAUtils.decryptDataOnJava(accessBind.getCvv2(), PayConstants.CARD_RSA_PRIVATE_KEY_PKCS8));
            }
            if (!StringUtils.isEmpty(accessBind.getValidity())) {
                accessBind.setValidity(RSAUtils.decryptDataOnJava(accessBind.getValidity(), PayConstants.CARD_RSA_PRIVATE_KEY_PKCS8));
            }
            payRequest.setCvv2(accessBind.getCvv2());
            payRequest.setMonth(StringUtils.isEmpty(accessBind.getValidity()) ? "" : accessBind.getValidity().substring(0, 2));
            payRequest.setYear(StringUtils.isEmpty(accessBind.getValidity()) ? "" : accessBind.getValidity().substring(2, 4));
        }
        order.setPayBank(accessBind.getCardName());
        order.setPayCardNo(accessBind.getCardNum());
        avsPayOrderService.update(order);
        RestResponse restResponse = createPay(payRequest);
        RestResponse orderRes = hlbService.orderQuery(order.getOrderNum());
        if (restResponse.getCode().equals("20002") && Objects.equals(order.getStatus(), Enums.OrderStatusEnum.NO_PAYED.getValue()) && orderRes.getCode().equals("200")) {
            HlbOrderQueryResponse response = (HlbOrderQueryResponse) orderRes.getResult();
            if (response.getRt9_orderStatus().equals("INIT")) {
                Map<String, String> params = new HashMap<>();
                params.put("orderNum", order.getOrderNum());
                params.put("amount", order.getAmountTotal().toString());
                params.put("cardNum", order.getPayCardNo().substring(0, 4) + "********" + order.getPayCardNo().substring(order.getPayCardNo().length() - 4));
                restResponse = RestResponse.build(params);
            }
        }
        return restResponse;
    }

    // 绑卡支付
    public RestResponse bindCardPay(BindCardPayRequest bindCardPayRequest) {
        RestResponse restResponse = null;
        bindCardPayRequest.setServerCallBackUrl(serverUrl + "/thmlfApi/avs/hlbquick/hlbasyncpaynotify");
        AvsPayOrder order = avsPayOrderService.findByOrderNum(bindCardPayRequest.getOrderNum()).get(0);
        if (AccessEnums.gatewayEnum.HLB_QUICK.getValue().equals(bindCardPayRequest.getGateway())) {
            HlbBindCardPayRequest request = new HlbBindCardPayRequest();
            request.setP3_bindId(bindCardPayRequest.getBindId());
            request.setP4_userId(order.getPayerId());
            request.setP5_orderId(order.getOrderNum());
            request.setP8_orderAmount(order.getAmountTotal().toString());
            request.setP9_goodsName(order.getRemark());
            request.setP10_goodsDesc(order.getRemark());
            request.setP11_terminalType(bindCardPayRequest.getTerminalType());
            request.setP12_terminalId(bindCardPayRequest.getTerminalId());
            request.setP13_orderIp(bindCardPayRequest.getOrderIp());
            request.setP16_serverCallbackUrl(bindCardPayRequest.getServerCallBackUrl());
            request.setP17_validateCode(bindCardPayRequest.getValidateCode());
            restResponse = hlbService.bindCardPay(request);
            if (restResponse.getCode().equals(String.valueOf(HttpStatus.OK.value()))) {
                HlbBindCardPayResponse hlbConfirmPayResponse = (HlbBindCardPayResponse) restResponse.getResult();
                List<AvsPayOrder> orderList = avsPayOrderService.findByOrderNum(hlbConfirmPayResponse.getRt5_orderId());
                if (orderList.isEmpty()) {
                    return restResponse;
                }
                AvsPayOrder payOrder = orderList.get(0);
                if (hlbConfirmPayResponse.getRt9_orderStatus().equals("SUCCESS")) {
                    payOrder.setStatus(Enums.OrderStatusEnum.SUCCESS_PAYED.getValue());
                } else if (hlbConfirmPayResponse.getRt9_orderStatus().equals("INIT")) {
                    payOrder.setStatus(Enums.OrderStatusEnum.NO_PAYED.getValue());
                } else if (hlbConfirmPayResponse.getRt9_orderStatus().equals("FAILED")) {
                    payOrder.setStatus(Enums.OrderStatusEnum.FAILED.getValue());
                } else if (hlbConfirmPayResponse.getRt9_orderStatus().equals("CANCELLED")) {
                    payOrder.setStatus(Enums.OrderStatusEnum.CANCEL.getValue());
                } else if (hlbConfirmPayResponse.getRt9_orderStatus().equals("REFUNDED")) {
                    payOrder.setStatus(Enums.OrderStatusEnum.REFUND.getValue());

                } else if (hlbConfirmPayResponse.getRt9_orderStatus().equals("DOING")) {
                    payOrder.setStatus(Enums.OrderStatusEnum.DOING.getValue());
                }
                payOrder.setOutTradeNum(hlbConfirmPayResponse.getRt6_serialNumber());
                payOrder.setTransDate(DateUtils.toDate(hlbConfirmPayResponse.getRt7_completeDate()));
                payOrder.setFinishDate(DateUtils.toDate(hlbConfirmPayResponse.getRt7_completeDate()));
                avsPayOrderService.update(payOrder);
            }
        }
        return restResponse;
    }

    // 发送验证码
    public RestResponse sendPayCode(String phone, String orderNum, String gateway) {
        if (AccessEnums.gatewayEnum.HLB_QUICK.getValue().equals(gateway)) {
            HlbSendPayCodeRequest request = new HlbSendPayCodeRequest();
            request.setP3_orderId(orderNum);
            request.setP5_phone(phone);
            return hlbService.sendPayCode(request);
        }
        return null;
    }

    // 绑卡支付验证码
    @Transactional
    public RestResponse bindCardPaySms(String phone, String gateway, String bindId, String orderNum) {
        AvsPayOrder order = avsPayOrderService.findByOrderNum(orderNum).get(0);
        List<AccessBind> accessBind = accessService.findAccessBindByBindId(bindId);
        if (accessBind.isEmpty()) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "银行卡信息有误");
        }
        order.setPayBank(accessBind.get(0).getCardName());
        order.setPayCardNo(accessBind.get(0).getCardNum());
        avsPayOrderService.update(order);
        if (AccessEnums.gatewayEnum.HLB_QUICK.getValue().equals(gateway)) {
            HlbBindCardPaySmsRequest request = new HlbBindCardPaySmsRequest();
            request.setP3_bindId(bindId);
            request.setP4_userId(order.getPayerId());
            request.setP5_orderId(order.getOrderNum());
            request.setP8_orderAmount(order.getAmountTotal().toString());
            request.setP9_phone(phone);
            return hlbService.bindCardPaySms(request);
        }
        return null;
    }


    // 完成支付
    @Transactional
    public RestResponse confirmPay(ConfirmPayRequest confirmPayrequest) {
        RestResponse restResponse = null;
        if (AccessEnums.gatewayEnum.HLB_QUICK.getValue().equals(confirmPayrequest.getGateway())) {
            List<Access> accessList = accessService.findByGateway(confirmPayrequest.getGateway());
            if (accessList.isEmpty()) {
                return RestResponse.build(RestResponse.AVS_ERROR_CODE, "支付环境异常");
            }
            Access access = accessList.get(0);
            HlbConfirmPayRequest request = new HlbConfirmPayRequest();
            request.setP3_orderId(confirmPayrequest.getOrderNum());
            request.setP5_validateCode(confirmPayrequest.getValidateCode());
            request.setP6_orderIp(confirmPayrequest.getOrderIp());
            restResponse = hlbService.confirmPay(request);
            if (restResponse.getCode().equals(String.valueOf(HttpStatus.OK.value()))) {
                HlbConfirmPayResponse hlbConfirmPayResponse = (HlbConfirmPayResponse) restResponse.getResult();
                Map params = new HashMap();
                params.put("payerId", hlbConfirmPayResponse.getRt14_userId());
                params.put("bankCode", hlbConfirmPayResponse.getRt11_bankId());
                params.put("cardAfterFour", hlbConfirmPayResponse.getRt13_cardAfterFour());
                params.put("cardType", hlbConfirmPayResponse.getRt12_onlineCardType().equals("CREDIT") ? "X" : "J");
                List<AccessBind> accessBindList = accessService.findByParams(params);
                AccessBind accessBind = accessBindList.isEmpty() ? null : accessBindList.get(0);
                List<AccessBank> accessBankList = accessService.findByAccessIdAndBankCode(access.getAccessId(), hlbConfirmPayResponse.getRt11_bankId());
                List<AvsPayOrder> orderList = avsPayOrderService.findByOrderNum(hlbConfirmPayResponse.getRt5_orderId());
                if (orderList.isEmpty()) {
                    return restResponse;
                }
                AvsPayOrder payOrder = orderList.get(0);
                if (hlbConfirmPayResponse.getRt9_orderStatus().equals("SUCCESS")) {
                    payOrder.setStatus(Enums.OrderStatusEnum.SUCCESS_PAYED.getValue());
                } else if (hlbConfirmPayResponse.getRt9_orderStatus().equals("INIT")) {
                    payOrder.setStatus(Enums.OrderStatusEnum.NO_PAYED.getValue());
                } else if (hlbConfirmPayResponse.getRt9_orderStatus().equals("CANCELLED")) {
                    payOrder.setStatus(Enums.OrderStatusEnum.CANCEL.getValue());
                } else if (hlbConfirmPayResponse.getRt9_orderStatus().equals("REFUNDED")) {
                    payOrder.setStatus(Enums.OrderStatusEnum.REFUND.getValue());
                } else if (hlbConfirmPayResponse.getRt9_orderStatus().equals("FAILED")) {
                    payOrder.setStatus(Enums.OrderStatusEnum.FAILED.getValue());
                } else if (hlbConfirmPayResponse.getRt9_orderStatus().equals("DOING")) {
                    payOrder.setStatus(Enums.OrderStatusEnum.DOING.getValue());
                }
                payOrder.setOutTradeNum(hlbConfirmPayResponse.getRt6_serialNumber());
                payOrder.setTransDate(DateUtils.toDate(hlbConfirmPayResponse.getRt7_completeDate()));
                avsPayOrderService.update(payOrder);
                if (accessBind == null) {
                    accessBind = new AccessBind();
                    accessBind.setAccessBindId(IDUtils.getPK());
                    accessBind.setBindId(hlbConfirmPayResponse.getRt10_bindId());
                    accessBind.setLastFourNum(hlbConfirmPayResponse.getRt13_cardAfterFour());
                    accessBind.setAccessId(access.getAccessId());
                    accessBind.setPayerId(hlbConfirmPayResponse.getRt14_userId());
                    if (accessBankList.isEmpty()) {
                        return restResponse;
                    }
                    accessBind.setCardName(accessBankList.get(0).getBankName());
                    accessBind.setCardCode(accessBankList.get(0).getBankCode());
                    accessBind.setHoldName(confirmPayrequest.getHoldName());
                    accessBind.setPhone(confirmPayrequest.getPhone());
                    accessBind.setCardType(hlbConfirmPayResponse.getRt12_onlineCardType().equals("DEBIT") ? "J" : "X");
                    accessService.save(accessBind);
                } else {
                    accessBind.setBindId(hlbConfirmPayResponse.getRt10_bindId());
                    accessService.updateBind(accessBind);
                }
            }
        }
        return restResponse;
    }

    // 绑定结算卡
    public RestResponse bindDepositCard(BindDepositCardRequest request) {
        List<AvsPayCashBind> avsPayCashBinds = avsPayCashBindService.findByCashBinIdAndPayerIdAndIsDeposit(request.getPayerId(), request.getCashBindId(), 1);
        if (avsPayCashBinds.isEmpty()) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "绑卡失败");
        }
        HlbBindBankCardRequest bindBankCardRequest = new HlbBindBankCardRequest();
        bindBankCardRequest.setP3_userId(request.getPayerId());
        bindBankCardRequest.setP4_orderId(IDUtils.getUniqueNum14());
        bindBankCardRequest.setP5_payerName(avsPayCashBinds.get(0).getHoldName());
        bindBankCardRequest.setP7_idCardNo(avsPayCashBinds.get(0).getIdCard());
        bindBankCardRequest.setP8_cardNo(avsPayCashBinds.get(0).getCardNum());
        bindBankCardRequest.setP9_phone(avsPayCashBinds.get(0).getPhone());
        return hlbService.bindDepositCard(bindBankCardRequest, "ADD");
    }

    // 确认支付短信
    public RestResponse confirmPayMs(ConfirmPayMsRequest request) {
        List<AvsPayOrder> orders = avsPayOrderService.findByOrderNum(request.getOrderNum());

        if (!orders.isEmpty()) {
            RestResponse restResponse = null;
            AvsPayOrder order = orders.get(0);
            if (StringUtils.isEmpty(request.getBindId()) || request.getBindId().equals("null")) {
                ConfirmPayRequest confirmPayRequest = new ConfirmPayRequest();
                confirmPayRequest.setPhone(request.getPhone());
                confirmPayRequest.setHoldName(request.getHoldName());
                confirmPayRequest.setGateway(request.getGateway());
                confirmPayRequest.setOrderIp(order.getOrderIp());
                confirmPayRequest.setOrderNum(order.getOrderNum());
                confirmPayRequest.setRememberCard(request.getRememberCard());
                confirmPayRequest.setValidateCode(request.getValidateCode());
                restResponse = confirmPay(confirmPayRequest);
            } else {
                BindCardPayRequest bindCardPayRequest = new BindCardPayRequest();
                bindCardPayRequest.setValidateCode(request.getValidateCode());
                bindCardPayRequest.setGateway(request.getGateway());
                bindCardPayRequest.setOrderNum(order.getOrderNum());
                bindCardPayRequest.setOrderIp(order.getOrderIp());
                bindCardPayRequest.setTerminalType(request.getTerminalType());
                bindCardPayRequest.setTerminalId(request.getTerminalId());
                bindCardPayRequest.setGoodsName(order.getRemark());
                bindCardPayRequest.setBindId(request.getBindId());
                bindCardPayRequest.setGoodsDesc(order.getRemark());
                bindCardPayRequest.setServerCallBackUrl(serverUrl + "/thmlfApi/avs/hlbquick/hlbasyncpaynotify");
                restResponse = bindCardPay(bindCardPayRequest);
            }
//            if (order.getRemark().equals(PayConstants.VIP_CASH)) {
//                List<AvsPayVip> vips = avsPayVipService.findByUserId(order.getPayerId());
//                if (vips.size() == 0)
//                    return RestResponse.build(RestResponse.AVS_ERROR_CODE, "刷卡成功，但信息错误，请联系客服处理");
//                AvsPayVip payVip = vips.get(0);
//                payVip.setStatus(AvsPayVipStatus.VipStatus.VIP.getValue());
//                Date nowDate = new Date();
//                Calendar c = Calendar.getInstance();
//                //一年后
//                c.setTime(nowDate);
//                c.add(Calendar.YEAR, 1);
//                Date nextYear = c.getTime();
//                payVip.setPayTime(nowDate);
//                payVip.setEndTime(nextYear);
//                payVip.setMoney(order.getAmountTotal());
//                avsPayVipService.update(payVip);
//                order.setStatus(Enums.OrderStatusEnum.VIP_SUCCESS.getValue());
//                avsPayOrderService.update(order);
//                return RestResponse.build("缴费成功");
//            } else {
//                if (restResponse != null && restResponse.getCode().equals(String.valueOf(HttpStatus.OK.value()))) {
//                    DepositRequest depositRequest = new DepositRequest();
//                    depositRequest.setPayerId(orders.get(0).getPayerId());
//                    depositRequest.setAmount(orders.get(0).getAmountTotal().toString());
//                    depositRequest.setSummary("极速支付提现");
//                    depositRequest.setOrderNum(orders.get(0).getOrderNum());
//                    restResponse = payBusiness.deposit(depositRequest);
//                }
//            }
            return restResponse;
        }
        return RestResponse.build(RestResponse.AVS_ERROR_CODE, "订单信息有误");
    }

    // 异步通知
    public String hlbAsyncPayNotify(AsyncPayNotifyRequest request) {
        String[] excludes = {"rt3_retMsg"};
        log.warn("---------------------------------------------------");
        log.warn("合力宝支付通知:" + new Gson().toJson(request));
        try {
            String responseSign = request.getSign();
            String assemblyRespOriSign = HlbBeanUtils.getSigned(request, null, PayConstants.HLB_SIGNKEY_SAME_PERSON);
            String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
            if (checkSign.equals(responseSign)) {
                if (request.getRt2_retCode().equals("0000")) {
                    List<AvsPayOrder> orders = avsPayOrderService.findByOrderNum(request.getRt5_orderId());
                    if (orders.isEmpty()) {
                        return "error";
                    }
                    AvsPayOrder order = orders.get(0);
                    log.warn("订单信息:" + new Gson().toJson(order));
                    if (request.getRt9_orderStatus().equals("INIT")) {
                        // 未支付
                        order.setStatus(Enums.OrderStatusEnum.NO_PAYED.getValue());
                        avsPayOrderService.update(order);
                        log.warn("订单取消");
                    } else if (request.getRt9_orderStatus().equals("SUCCESS")) {
                        // 支付成功
                        log.warn("订单成功");
                        if (order.getStatus().equals(Enums.OrderStatusEnum.SUCCESS_DEPOSIT.getValue())
                                || order.getStatus().equals(Enums.OrderStatusEnum.VIP_SUCCESS.getValue())
                                || order.getStatus().equals(Enums.OrderStatusEnum.SUCCESS_REWAARD.getValue())) {
                            log.warn("订单已处理");
                            return "success";
                        } else {
                            order.setStatus(Enums.OrderStatusEnum.SUCCESS_PAYED.getValue());
                            avsPayOrderService.update(order);
                            log.warn("订单处理为：支付成功-未提现");
                        }
                        if (order.getRemark().equals(PayConstants.VIP_CASH)) {
                            List<AvsPayVip> vips = avsPayVipService.findByUserId(order.getPayerId());
                            if (vips.size() == 0)
                                return "error";
                            AvsPayVip payVip = vips.get(0);
                            payVip.setStatus(AvsPayVipStatus.VipStatus.VIP.getValue());
                            Date nowDate = new Date();
                            Calendar c = Calendar.getInstance();
                            //一年后
                            c.setTime(nowDate);
                            c.add(Calendar.YEAR, 1);
                            Date nextYear = c.getTime();
                            payVip.setPayTime(nowDate);
                            payVip.setEndTime(nextYear);
                            payVip.setMoney(order.getAmountTotal());
                            avsPayVipService.update(payVip);
                            order.setStatus(Enums.OrderStatusEnum.VIP_SUCCESS.getValue());
                            avsPayOrderService.update(order);
                            log.warn("订单VIP缴费");
                        } else {
                            DepositRequest depositRequest = new DepositRequest();
                            depositRequest.setPayerId(orders.get(0).getPayerId());
                            depositRequest.setAmount(orders.get(0).getAmountTotal().toString());
                            depositRequest.setSummary("极速支付提现");
                            depositRequest.setOrderNum(orders.get(0).getOrderNum());
                            RestResponse restResponse = payBusiness.deposit(depositRequest);
                            System.out.println(new Gson().toJson(restResponse));
                            log.warn("提现res:" + new Gson().toJson(restResponse));
                        }
                    } else if (request.getRt9_orderStatus().equals("DOING")) {
                        // 处理中
                        order.setStatus(Enums.OrderStatusEnum.DOING.getValue());
                        avsPayOrderService.update(order);
                        log.warn("订单处理中");
                    } else if (request.getRt9_orderStatus().equals("CANCELLED")) {
                        // 取消
                        order.setStatus(Enums.OrderStatusEnum.CANCEL.getValue());
                        avsPayOrderService.update(order);
                        log.warn("订单取消");
                    } else if (request.getRt9_orderStatus().equals("REFUNDED")) {
                        // 退款
                        order.setStatus(Enums.OrderStatusEnum.REFUND.getValue());
                        avsPayOrderService.update(order);
                        log.warn("订单退款");
                    } else if (request.getRt9_orderStatus().equals("FAILED")) {
                        // 失败
                        order.setStatus(Enums.OrderStatusEnum.FAILED.getValue());
                        avsPayOrderService.update(order);
                        log.warn("订单失败");
                    }
                    log.warn("通知处理成功");
                    log.warn("---------------------------------------------");
                    return "success";
                } else {
                    return "error";
                }
            } else {
                log.warn("通知签名验证失败");
            }
            return "error";
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getLocalizedMessage() + ":" + e.getMessage() + ":" + e.getCause());
            return "error";
        }
    }


    // 代付提现
    @Transactional
    public RestResponse deposit(DepositRequest request) {
        List<AvsPayCashBind> avsPayCashBinds = avsPayCashBindService.findByCashBinIdAndIsDeposit(request.getPayerId(), 1);
        if (avsPayCashBinds.isEmpty()) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "结算卡未设置");
        }
        AvsCustomer customer = avsCustomerService.findByCustomerId(request.getPayerId());
        //绑卡
        HlbBindBankCardRequest bindBankCardRequest = new HlbBindBankCardRequest();
        bindBankCardRequest.setP3_userId(request.getPayerId());
        bindBankCardRequest.setP4_orderId(IDUtils.getUniqueNum14());
        bindBankCardRequest.setP5_payerName(customer.getCustomerName());
        bindBankCardRequest.setP7_idCardNo(customer.getIdCard());
        bindBankCardRequest.setP8_cardNo(avsPayCashBinds.get(0).getCardNum());
        bindBankCardRequest.setP9_phone(avsPayCashBinds.get(0).getPhone());
        RestResponse bindResponse = hlbService.bindDepositCard(bindBankCardRequest, "ADD");
        if (bindResponse != null && bindResponse.getCode().equals(String.valueOf(HttpStatus.OK.value()))) {
            List<AvsPayOrder> orderList = avsPayOrderService.findByOrderNum(request.getOrderNum());
            RestResponse depositStatus = hlbService.transferQuery(request.getOrderNum());
            if (depositStatus != null && depositStatus.getResult() != null) {
                HlbTransferQueryResponse response = (HlbTransferQueryResponse) depositStatus.getResult();
                if (!response.getRt2_retCode().equals("0005") && !response.getRt7_orderStatus().equals(AvsTransferStatus.TransferStatus.FAIL.getValue())) {
                    return RestResponse.build(RestResponse.AVS_ERROR_CODE, "该笔订单不满足提现要求");
                }
            }
            if (orderList.isEmpty() || (orderList.get(0).getStatus().intValue() != Enums.OrderStatusEnum.SUCCESS_PAYED.getValue() && orderList.get(0).getStatus().intValue() != Enums.OrderStatusEnum.DOING.getValue())) {
                return RestResponse.build(RestResponse.AVS_ERROR_CODE, "该笔订单不满足提现要求");
            } else {
                AvsPayOrder order = orderList.get(0);
                if (!order.getPayerId().equals(request.getPayerId())) {
                    return RestResponse.build(RestResponse.AVS_ERROR_CODE, "非法请求");
                }
                order.setCashCardNo(avsPayCashBinds.get(0).getCardNum());
                order.setCollecBank(avsPayCashBinds.get(0).getBankName());
                avsPayOrderService.update(order);
                HlbDepositRequest hlbDepositRequest = new HlbDepositRequest();
                hlbDepositRequest.setP3_userId(request.getPayerId());
                hlbDepositRequest.setP4_orderId(request.getOrderNum());
                hlbDepositRequest.setP5_amount(order.getRealAmount().toString());
                hlbDepositRequest.setP7_summary(request.getSummary());
                RestResponse restResponse = hlbService.deposit(hlbDepositRequest);
                if (restResponse != null && restResponse.getCode().equals(String.valueOf(HttpStatus.OK.value()))) {
                    HlbDepositResponse hlbDepositResponse = (HlbDepositResponse) restResponse.getResult();
                    if (hlbDepositResponse.getRt2_retCode().equals("0000")) {
                        if (order.getRemark().equals(PayConstants.VIP_REWARD))
                            order.setStatus(Enums.OrderStatusEnum.SUCCESS_REWAARD.getValue());
                        else
                            order.setStatus(Enums.OrderStatusEnum.SUCCESS_DEPOSIT.getValue());
                        order.setFinishDate(new Date());
                        if (request.getIsRedeposit() == 1) {
                            order.setIsRedeposit(request.getIsRedeposit());
                            order.setRedepositDate(new Date());
                        }
                        avsPayOrderService.update(order);
                        restResponse = RestResponse.build(hlbDepositResponse);
                    } else {
                        Gson gson = new Gson();
                        String content = "合利宝代付提现失败：" + order.getOrderNum() + "--" + gson.toJson(hlbDepositRequest) + "--" + gson.toJson(hlbDepositResponse);
                        log.warn(content);
                    }
                    return restResponse;
                } else {
                    return restResponse;
                }
            }

        }
        return bindResponse;
    }
}